﻿using FitnessDiary.Domain.Abstract;
using FitnessDiary.Domain.Entities;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace FitnessDiary.Domain.Concrete
{
	public class FitnessDiaryRepository : IFitnessDiaryRepository
	{
		private FitnessDiaryDBContext db = new FitnessDiaryDBContext();

		public IQueryable<Unit> Units
		{
			get { return db.Units; }
		}

		public IQueryable<HitComponent> HitComponents
		{
			get { return db.HitComponents; }
		}

		public IQueryable<Hit> Hits
		{
			get { return db.Hits; }
		}

		public IQueryable<Stat> Stats
		{
			get { return db.Stats; }
		}

		public IQueryable<Quantity> Quantities
		{
			get { return db.Quantities; }
		}

		public void SaveStat(Stat stat)
		{
			if (stat.Quantities != null)
			{
				foreach (Quantity q in stat.Quantities)
				{
					Unit unit = db.Units.Where(u => u.Id == q.Unit.Id).FirstOrDefault();
					if (unit != null)
					{
						q.Unit = unit;
					}
				}
			}
			db.Stats.Add(stat);
			db.SaveChanges();
		}

		public void UpdateStat(Stat stat)
		{
			var quantities = stat.Quantities;
			if (quantities != null)
			{
				foreach (Quantity q in stat.Quantities)
				{
					UpdateQuantity(q);
				}
			}
			db.Entry(stat).State = EntityState.Modified;
			db.SaveChanges();
		}

		public void DeleteStat(Stat stat)
		{
			db.Stats.Remove(stat);
			db.SaveChanges();
		}

		public void SaveHit(Hit hit)
		{
			db.Hits.Add(hit);
			db.SaveChanges();
		}

		public void UpdateHit(Hit hit)
		{
			db.Entry(hit).State = EntityState.Modified;
			db.SaveChanges();
		}

		public void DeleteHit(Hit hit)
		{
			db.Hits.Remove(hit);
			db.SaveChanges();
		}

		public void UpdateQuantity(Quantity quantity)
		{
			db.Entry(quantity).State = EntityState.Modified;
			db.SaveChanges();
		}

		public void DeleteQuantity(Quantity quantity)
		{
			db.Quantities.Remove(quantity);
			db.SaveChanges();
		}

		public void DeleteHitComponent(HitComponent hitComponent)
		{
			db.HitComponents.Remove(hitComponent);
			db.SaveChanges();
		}

		public void Dispose()
		{
			db.Dispose();
		}

		public Stat GetStat(int id)
		{
			Stat stat = db.Stats.Where(s => s.Id == id).FirstOrDefault();
			List<Quantity> quantities = db.Quantities.Where(q => q.Stat.Id == id).ToList();
			return stat;
		}
	}
}
